package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.swing.plaf.basic.BasicTreeUI;

/**
 * 设备管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-12-13
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private Client client;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    /**
     * 查询设备管理
     * 
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备管理列表
     * 
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备管理
     * 
     * @param deviceDto 设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(DeviceDto deviceDto)  {
        BatchUpdateDeviceNicknameRequest resquset = new BatchUpdateDeviceNicknameRequest();
        resquset.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        List<BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo> deviceInfoList = new ArrayList<>();
        Map deviceMap = new HashMap<>();
        deviceMap.put("deviceName", deviceDto.getDeviceName());
        deviceMap.put("productKey", deviceDto.getProductKey());
        deviceMap.put("nickname", deviceDto.getNickname());
        BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo info = null;
        try {
            info = BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo.build(deviceMap);
        } catch (Exception e) {
            throw new BaseException("修改设备昵称失败");
        }
        deviceInfoList.add(info);
        resquset.setDeviceNicknameInfo(deviceInfoList);
        BatchUpdateDeviceNicknameResponse response;
        try {
            response = client.batchUpdateDeviceNickname(resquset);
            Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceDto.iotId));
            BeanUtils.copyProperties(deviceDto, device);
            updateById(device);
        } catch (Exception e) {
            throw new BaseException("修改设备昵称失败");
        }

        if(!response.getBody().success){
            throw new BaseException("修改设备昵称失败");
        }

        return 1;
    }

    /**
     * 批量删除设备管理
     * 
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备管理信息
     * 
     * @param deviceDto 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(DeviceDto deviceDto) {

        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setProductKey(deviceDto.getProductKey());
        request.setDeviceName(deviceDto.getDeviceName());
        request.setIotId(deviceDto.getIotId());
        DeleteDeviceResponse response;
        try {
            response= client.deleteDevice(request);
            Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceDto.getIotId()));
            BeanUtils.copyProperties(deviceDto, device);
            deleteDevice(device);
        } catch (Exception e) {
            throw new BaseException("删除设备失败");
        }
        if(!response.getBody().success){
            throw new BaseException("删除设备失败");
        }
        return 1;
    }


    /**
     * 从物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        // 请求参数
        QueryProductListRequest request = new QueryProductListRequest();
        request.setPageSize(200);
        request.setCurrentPage(1);
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        // 调用第三方查询产品列表
        QueryProductListResponse response ;
        try {
            response = client.queryProductList(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }

        // 判断，如果数据为空，则中断请求
        if(!response.getBody().success){
            throw new BaseException("物联网接口 - 查询产品，调用失败");
        }

        // 存储到redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_ALL, JSONUtil.toJsonStr(response.getBody().getData().getList().getProductInfo()));
    }

    /**
     * 查询所有产品
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        // 从redis中查询数据
        String jsonStr = (String) redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_ALL);
        // 如果数据为空，则返回一个空集合
        if(StringUtils.isEmpty(jsonStr)){
            return Collections.emptyList();
        }
        // 解析数据，并返回
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    /**
     * 注册设备
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //1、判断设备名称是否重复
        long count = count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if(count>0){
            throw new BaseException("设备名称重复，请重新输入");
        }
        //2、新增设备到物联网平台
        RegisterDeviceResponse response = insertIoTDevice(deviceDto);
        //3、判断保存设备到iot平台是否成功
        if(!response.getBody().success){
            throw new BaseException("设备注册失败，请重新尝试");
        }
        //4、查询产品数据
        QueryProductResponse queryProductResponse = selectProduct(deviceDto);
        //5、判断接口是否调通
        if(!queryProductResponse.getBody().success){
            throw new BaseException("物联网接口 - 查询产品，调用失败");
        }
        //6、设置产品名称到设备对象
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setProductName(queryProductResponse.getBody().getData().productName);

        // 物理位置
        if(device.getLocationType().equals(0)) {
            device.setPhysicalLocationType(-1);
        }
        // 补全设备id
        device.setIotId(response.getBody().getData().getIotId());
        // 保存设备
        try {
            device.setCreateTime(new Date());
            deviceMapper.insertDevice(device);
        }catch (Exception e){
            //7、删除iot中的设备
            deleteDevice(device);
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }
    }

    /**
     * 查询设备详情
     * @param deviceDto
     * @return
     */
    @Override
    public DeviceVo queryDeviceDetail(DeviceDto deviceDto) {
        //查询物联网中的数据
        QueryDeviceDetailResponse response = queryIotDevice(deviceDto);
        //判断接口是否调通
        if(!response.getBody().success){
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceDto.getIotId()));
        DeviceVo deviceVo = new DeviceVo();
        BeanUtils.copyProperties(device, deviceVo);

        QueryDeviceDetailResponseBody.QueryDeviceDetailResponseBodyData data = response.getBody().getData();
        BeanUtils.copyProperties(data, deviceVo);

        return deviceVo;
    }

    /**
     * 查询物模型
     * @param request
     * @return
     */
    @Override
    public AjaxResult queryThingModelPublished(QueryThingModelPublishedRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryThingModelPublishedResponse response;
        try {
            response = client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询物模型，调用失败");
        }

        if(!response.getBody().success){
            return AjaxResult.error(response.getBody().errorMessage);
        }
        return AjaxResult.success(response.getBody().getData());
    }

    /**
     * 查询设备属性
     * @param request
     * @return
     */
    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDevicePropertyStatusResponse response;
        try {
            response = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备属性，调用失败");
        }

        if(!response.getBody().success){
            throw new BaseException(response.getBody().getErrorMessage());
        }
        return AjaxResult.success(response.getBody().getData());
    }

    /**
     * 查询设备详细信息
     * @param deviceDto
     */
    private QueryDeviceDetailResponse queryIotDevice(DeviceDto deviceDto) {
        QueryDeviceDetailRequest request = new QueryDeviceDetailRequest();
        request.setIotId(deviceDto.getIotId());
        request.setProductKey(deviceDto.getProductKey());
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDeviceDetailResponse response;
        try {
            response = client.queryDeviceDetail(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }
        return response;
    }

    /**
     * 抽取的方法三：删除设备
     * @param device
     */
    private void deleteDevice(Device device) {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceName(device.getDeviceName());
        request.setProductKey(device.getProductKey());
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setIotId(device.getIotId());
        DeleteDeviceResponse response;
        try {
            response = client.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 删除设备，调用失败");
        }
    }

    /**
     * 抽取的方法二：查询产品数据
     * @param deviceDto
     * @return
     */
    private QueryProductResponse selectProduct(DeviceDto deviceDto) {

        QueryProductRequest request = new QueryProductRequest();
        request.setProductKey(deviceDto.getProductKey());
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryProductResponse response;
        try {
             response= client.queryProduct(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询产品，调用失败");
        }
        return response;
    }

    /**
     * 抽取的方法一：新增设备到物联网平台
     * @param deviceDto
     * @return
     */
    private RegisterDeviceResponse insertIoTDevice(DeviceDto deviceDto) {
        RegisterDeviceRequest request = deviceDto.getRegisterDeviceRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        RegisterDeviceResponse response;
        try {
             response = client.registerDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }
        return response;
    }
}
